from User import User
from Account import Account, AccountManager

# 初始化 AccountManager
account_manager = AccountManager("E:\\桌面\\Python基础准备")

# 最大尝试次数
MAX_ATTEMPTS = 3


# 打印欢迎界面
def print_welcome():
    print("#############################")
    print("#                           #")
    print("#   欢迎来到度小满家庭对账系统   #")
    print("#                           #")
    print("#############################")


# 打印管理菜单
def print_admin_menu():
    print("############################################################")
    print("#                                                          #")
    print("#                  欢迎进入度小满家庭对账系统                   #")
    print("#                                                          #")
    print("# 1. 添加账务   2. 编辑账务  3. 删除账务  4. 查询账务  5. 退出系统 #")
    print("#                                                          #")
    print("############################################################")


# 打印用户菜单
def print_user_menu():
    print("###############################")
    print("#                             #")
    print("#    欢迎进入度小满家庭对账系统    #")
    print("#   1. 查询所有   2. 按条件查询   #")
    print("#   3. 退出系统                 #")
    print("###############################")


# 打印所有账务
def print_accounts():
    accounts = account_manager.get_all_accounts()
    if accounts:
        print("=" * 20)
        print(
            "账户ID" + " " * 4 + "交易类别" + " " * 4 + "账户" + " " * 4 + "交易金额" + " " * 4 + "时间" + " " * 4 + "交易描述")
        for account in accounts:
            print(
                " " * 2 + account.account_id + " " * 6 + account.category + " " * 4 + account.account + " " * 4 + str(
                    account.amount) + " " * 4 + account.timestamp + " " * 4 + account.description)
        print("=" * 20)
    else:
        print("没有账务记录")
    input("按任意键继续\n")


def print_account_by_id():
    account_id = input("请输入要查询的账户ID: ")
    account = account_manager.get_account(account_id)
    if account:
        print("=" * 20)
        print(f"账户ID: {account.account_id}")
        print(f"交易类别: {account.category}")
        print(f"账户名称或编号: {account.account}")
        print(f"交易金额: {account.amount}")
        print(f"时间戳: {account.timestamp}")
        print(f"交易描述: {account.description}")
        print("=" * 20)
    else:
        print("未找到该账务")
    input("按任意键继续\n")


# 处理用户菜单选项
def handle_user_menu_option(option):
    # 处理有效的选项
    if option == '1':
        print_accounts()
    elif option == '2':
        print_account_by_id()
    elif option == '3':
        print("欢迎下次再来")
        exit()
    else:
        print("输入有误，请重新输入")


def add_account():
    # 添加账务功能
    account_id = input("请输入账户ID: ")
    category = input("请输入交易类别: ")
    account = input("请输入账户名称或编号: ")
    amount = float(input("请输入交易金额: "))
    timestamp = input("请输入时间戳: ")
    description = input("请输入交易描述: ")
    new_account = Account(account_id, category, account, amount, timestamp, description)
    account_manager.add_account(new_account)
    print("账务添加成功")


def remove_account():
    # 删除账务功能
    account_id = input("请输入要删除的账户ID: ")
    user_tag = User.search_user_by_id(account_id)
    account_manager.remove_account(account_id)
    print("账务删除成功")


def edit_account():
    # 编辑账务功能
    account_id = input("请输入要编辑的账户ID: ")
    print("请输入要更新的字段和新值（按回车跳过）:")
    category = input("交易类别: ") or None
    account = input("账户名称或编号: ") or None
    amount = input("交易金额: ")
    amount = float(amount) if amount else None
    timestamp = input("时间戳: ") or None
    description = input("交易描述: ") or None
    updates = {k: v for k, v in locals().items() if
               k in ['category', 'account', 'amount', 'timestamp', 'description'] and v is not None}
    account_manager.update_account(account_id, **updates)
    print("账务更新成功")


# 处理管理菜单选项
def handle_admin_menu_option(option):
    if option == "1":
        add_account()
    elif option == "2":
        edit_account()
    elif option == "3":
        remove_account()
    elif option == "4":
        # 查询账务功能
        query_type = input("请输入查询类型（1: 根据ID查询, 2: 查询所有账务）: ")
        if query_type == "1":
            print_account_by_id()
        elif query_type == "2":
            print_accounts()
        else:
            print("输入的查询类型有误，请重新输入")
    elif option == "5":
        print("欢迎下次再来")
        exit()
    else:
        print("输入有误，请重新输入")


# 主函数
def main():
    attempts = 0
    user = None
    while attempts < MAX_ATTEMPTS:
        print_welcome()
        username = input("请输入你的用户名\n")
        if not username:
            print("用户名不能为空，请重新输入")
            continue
        try:
            user_tag = User.search_user(username)
        except Exception as e:
            print(f"搜索用户时发生错误: {e}")
            continue

        if not user_tag:
            print("用户不存在，请重新输入")
            continue

        password = input("请输入你的密码\n")
        if not password:
            print("密码不能为空，请重新输入")
            continue
        try:
            user = User.login(username, password)
        except Exception as e:
            print(f"登录时发生错误: {e}")
            continue

        if user:
            print("登录成功")
            input("按任意键进入管理页面\n")
            break
        else:
            print("密码错误，请重新输入")
            if attempts == MAX_ATTEMPTS - 1:
                print("已超过最大尝试次数，请休息一下吧")
                exit()
            attempts += 1
            print(f"还有{MAX_ATTEMPTS - attempts}次机会")
    while True:
        if user and user.role == 'admin':
            print_admin_menu()
            option = input("请输入要操作的功能序号[1-5]:\t").strip()
            handle_admin_menu_option(option)
        elif user and user.role == 'user':
            print_user_menu()
            option = input("请输入要操作的功能序号[1-3]:\t").strip()
            handle_user_menu_option(option)


if __name__ == "__main__":
    main()
